package com.pointstar.dp.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 南软2003T2
 * 计算二叉树层次数
 *
 * @author 朱科睿
 */
public class TreeDepth {

    public static void main(String[] args) {
        TreeNode level3_1 = new TreeNode(31, null, null);
        TreeNode level3_2 = new TreeNode(32, null, null);
        TreeNode level2_1 = new TreeNode(21, level3_1, level3_2);
        TreeNode level2_2 = new TreeNode(22, null, null);
        TreeNode root = new TreeNode(1, level2_1, level2_2);
        System.out.printf("递归计算树有%s层%n", getTreeDepthRecursion(root));
        System.out.printf("非递归计算树有%s层", getTreeDepth(root));
    }

    /**
     * 递归法
     *
     * @param root 根节点
     * @return 节点所在层数
     */
    private static int getTreeDepthRecursion(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = getTreeDepthRecursion(root.left);
        int right = getTreeDepthRecursion(root.right);
        return Math.max(left, right) + 1;
    }

    /**
     * 非递归法
     *
     * @param root 根节点
     * @return 二叉树层数
     */
    private static int getTreeDepth(TreeNode root) {
        if (root == null)
            return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int dep = 0, count = 0, nextCount = 1;
        while (queue.size() != 0) {
            TreeNode top = queue.poll();
            count++;
            if (top.left != null) {
                queue.add(top.left);
            }
            if (top.right != null) {
                queue.add(top.right);
            }
            if (count == nextCount) {
                count = 0;
                nextCount = queue.size();
                dep++;
            }
        }
        return dep;
    }


    static class TreeNode {

        private int value;
        private TreeNode left;
        private TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int value, TreeNode left, TreeNode right) {
            this.value = value;
            this.left = left;
            this.right = right;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public TreeNode getLeft() {
            return left;
        }

        public void setLeft(TreeNode left) {
            this.left = left;
        }

        public TreeNode getRight() {
            return right;
        }

        public void setRight(TreeNode right) {
            this.right = right;
        }

    }

}
